#include <jni.h>
#include <string>
// wmd_mp3
#include "lame/lame.h"
//#include "lame/lame.h"
#include "FDK_core.h"
#include <stdio.h>
#include "native-lib.h"
#include "mp3_encode.h"

extern "C" JNIEXPORT jstring JNICALL
Java_com_wmd102_encode_LameEncoder_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

// wmd_mp3
extern "C" JNIEXPORT jstring JNICALL
Java_com_wmd102_encode_LameEncoder_getLameVersion(
        JNIEnv* env,
        jobject /* this */) {
    const char * lameVersion = get_lame_version();
    char result[50] = "LAME: ";
    strcat(result, lameVersion);
    return env->NewStringUTF(result);
}

extern "C" JNIEXPORT jstring JNICALL
Java_com_wmd102_encode_LameEncoder_getFDKAACVersion(
        JNIEnv* env,
        jobject /* this */) {
    return env->NewStringUTF(get_fak_aac_version());
}


/**
 * ��̬ע��
 */
JNINativeMethod methods[] = {
        {"encode",  "(Ljava/lang/String;Ljava/lang/String;III)V", (void *) encode},
        {"destroy", "()V",                                        (void *) destroy}
};

/**
 * ��̬ע��
 * @param env
 * @return
 */
jint registerNativeMethod(JNIEnv *env) {
    jclass cl = env->FindClass("com/wmd102/encode/LameEncoder");
    if ((env->RegisterNatives(cl, methods, sizeof(methods) / sizeof(methods[0]))) < 0) {
        return -1;
    }
    return 0;
}

/**
 * ����Ĭ�ϻص�
 * @param vm
 * @param reserved
 * @return
 */
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
    JNIEnv *env = NULL;
    if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
        return -1;
    }
    //ע�᷽��
    if (registerNativeMethod(env) != JNI_OK) {
        return -1;
    }
    return JNI_VERSION_1_6;
}


Mp3Encoder *encoder = NULL;

JNIEXPORT void JNICALL encode(JNIEnv *env, jobject obj, jstring pcmFilePath, jstring mp3FilePath, jint sampleRate,
       jint channels,
       jint bitRate) {
    const char *pcmPath = env->GetStringUTFChars(pcmFilePath, NULL);
    const char *mp3Path = env->GetStringUTFChars(mp3FilePath, NULL);
    encoder = new Mp3Encoder();
    encoder->Init(pcmPath, mp3Path, sampleRate, channels, bitRate);
    //��ʼ����
    encoder->Encode();

    env->ReleaseStringUTFChars(pcmFilePath, mp3Path);
    env->ReleaseStringUTFChars(mp3FilePath, pcmPath);
}

JNIEXPORT void JNICALL destroy(JNIEnv * env, jobject obj) {
    if (NULL != encoder) {
        encoder->Release();
        encoder = NULL;
    }
}
